package com.example.demo.client;

import com.example.demo.util.AesEncryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * 发送密文的Http客户端
 */
@Component
public class AesEncryptHttpClient {

    private static final MediaType CONTENT_TYPE = MediaType.parseMediaType("text/plain;charset=UTF-8");

    private static final String ACCEPT_KEY = "Accept";

    private static final String ACCEPT_VALUE = MediaType.TEXT_PLAIN.toString();

    // 配置文件配置的需要调用的服务器地址
    @Value("${decrypt.serverHost}")
    private String serverHost;

    @Autowired
    private RestTemplate restTemplate;


    /**
     * POST提交请求，会对请求体加密，返回体解密
     *
     * @param apiPath 接口路径
     * @param requestString 未加密的字符串
     * @return 解密后的返回值
     */
    public String post(String apiPath ,String requestString){
        String encReq = AesEncryptUtils.encrypt(requestString);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(CONTENT_TYPE);
        headers.add(ACCEPT_KEY, ACCEPT_VALUE);
        HttpEntity<String> request = new HttpEntity<>(encReq, headers);

        ResponseEntity<String> returnData = restTemplate.postForEntity(serverHost + apiPath, request, String.class);

        return AesEncryptUtils.decrypt(returnData.getBody());
    }

}
